# 2020/7/26

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class MyTreeItem(QTreeWidgetItem):
    def __init__(self, parent, dataDict=None):
        super(MyTreeItem, self).__init__(parent)

        self.new_table(dataDict)

    def new_table(self, dataDict):
        # 设置数据层次结构
        model = QStandardItemModel()
        # 设置水平方向四个头标签文本内容
        model.setHorizontalHeaderLabels(['Attribute', 'Value'])
        if dataDict is None:
            stateText = QLabel()
            stateText.setStyleSheet("QLabel{\n"
            "    background:#6C6C6C;\n"
            "    color:white;\n"
            "    box-shadow: 1px 1px 3px rgba(0,0,0,0.3);font-size:18px;border-radius: 10px;font-family: 微软雅黑;\n"
            "}\n")
            stateText.setAlignment(Qt.AlignCenter)
            stateText.setDisabled(1)
            stateText.setText("No details!It's just a title!")
            self.dataView = stateText
        else:
            # Todo 优化2 添加数据
            for key in dataDict.keys():
                # 筛选！
                if not isinstance(dataDict[key], str):
                    continue
                if dataDict[key] == '':
                    dataDict[key] = 'UNKNOWN'

                model.appendRow([
                    QStandardItem(key),
                    QStandardItem(dataDict[key])
                ])

            # 实例化表格视图，设置模型为自定义的模型
            tableView = QTableView()
            tableView.setStyleSheet("QTableView{\n"
            "    background:#6C6C6C;\n"
            "    color:white;\n"
            "    box-shadow: 1px 1px 3px rgba(0,0,0,0.3);font-size:18px;border-radius: 10px;font-family: 微软雅黑;\n"
            "}\n"
            )
            tableView.setModel(model)

            # todo 优化1 表格填满窗口
            # 水平方向标签拓展剩下的窗口部分，填满表格
            tableView.horizontalHeader().setStretchLastSection(True)
            # 水平方向，表格大小拓展到适当的尺寸
            tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            tableView.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)

            self.dataView = tableView

